﻿
using NP.BPMReportPlatform.AUTO;
using NP.BPMReportPlatform.AUTO.Adjust.Dto;
using NP.BPMReportPlatform.AUTO.Quotation.Dto;
using NP.BPMReportPlatform.AUTO.TechnicalDependence.Dto;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Engine;
using NP.BPMReportPlatform.CommonEnum;
using NP.BPMReportPlatform.FlowManagement.Dto;
using NP.BPMReportPlatform.IC.ICZHYLS.Dto;
using NP.BPMReportPlatform.IUDefectiveProduct.Dto;
using NP.BPMReportPlatform.IUTS;
using NP.BPMReportPlatform.IUTS.Dto;
using NP.BPMReportPlatform.Utils;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
namespace NP.BPMReportPlatform.IUDefectiveProduct
{
    public class IUDefectiveProductAppService : BPMReportPlatformAppService, IIUDefectiveProductAppService
    {
        private readonly SqlSugarClient _db, _dbEngine;
        private readonly IBPMUtilsAppService _bPMUtilsApp;
        private readonly IBPMPlatformAppService _iBPMPlatformApp;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sqlSugarAppService"></param>
        public IUDefectiveProductAppService(ISqlSugarAppService sqlSugarAppService, IBPMUtilsAppService bPMUtilsApp, IBPMPlatformAppService iBPMPlatformApp)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbEngine = sqlSugarAppService.GetEngineInstance();
            _bPMUtilsApp = bPMUtilsApp;
            _iBPMPlatformApp = iBPMPlatformApp;
        }

        #region  
        /// <summary>
        /// 获取Queryable
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private ISugarQueryable<IUDefectiveOutput> GetQueryable(GetIUDefectiveInput input)
        {

            var listQueryable = _db.Queryable<IUDefectiveProductHeader, BusinessProcessesNew>(
                    (x, bu) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == bu.InstanceId))

                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber),
                    (x, bu) => x.InstanceNumber.Contains(input.InstanceNumber))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), x => x.AddUserName.Equals(input.AddUserName))
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(), (x, bu) => SqlFunc.ContainsArray<string>(input.OrderStatus.ToArray(), bu.ProcessStatusName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.BusinessDivision), x => x.BusinessDivision.Equals(input.BusinessDivision))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Company), x => x.Company.Equals(input.Company))
                .WhereIF(!string.IsNullOrWhiteSpace(input.ProductName), x => x.ProductName.Equals(input.ProductName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.CustomerName), x => x.CustomerName.Equals(input.CustomerName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.ProductNo), x => x.ProductNo.Contains(input.ProductNo))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null, x => x.AddTime >= input.StartCreationTime && x.AddTime.AddDays(-1) <= input.EndCreationTime)

                .Select((x, bu) =>
                    new IUDefectiveOutput()
                    {
                        InstanceNumber = x.InstanceNumber,
                        BusinessDivision = x.BusinessDivision,
                        Company = x.Company,
                        BusinessDivisionType = x.BusinessDivisionType,
                        ProductNo = x.ProductNo,
                        CustomerName = x.CustomerName,
                        ProductName = x.ProductName,
                        ProductGZPC1 = x.ProductGZPC1,
                        OrderStatus = bu.ProcessStatusName,
                        CreateTime = bu.StartTime.ToString(),
                        UserName = bu.StartUserName,

                    }).MergeTable().Distinct().OrderBy(ins => ins.InstanceNumber, OrderByType.Desc);

            return listQueryable;
        }






        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<IUDefectiveOutput>> GetAllAsync(GetIUDefectiveInput input)
        {
            ////await UpdateOrderStatus(input);
            RefAsync<int> totalCount = 0;
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);
            listViewDto.ForEach(x =>
            {
                x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId);

            });



            //返回结果
            return new PagedResultDto<IUDefectiveOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }




        #endregion


        #region IU投诉报表导出GetQueryableExport1

        private ISugarQueryable<ExportIUDefectiveOutput> GetQueryableExport1(GetIUDefectiveInput input)
        {

            var listQueryable = _db.Queryable<IUDefectiveProductHeader, BusinessProcessesNew>(
                    (x, bu) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == bu.InstanceId))

                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber),
                    (x, bu) => x.InstanceNumber.Contains(input.InstanceNumber))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), x => x.AddUserName.Equals(input.AddUserName))
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(), (x, bu) => SqlFunc.ContainsArray<string>(input.OrderStatus.ToArray(), bu.ProcessStatusName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.BusinessDivision), x => x.BusinessDivision.Equals(input.BusinessDivision))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Company), x => x.Company.Equals(input.Company))
                .WhereIF(!string.IsNullOrWhiteSpace(input.ProductName), x => x.ProductName.Equals(input.ProductName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.CustomerName), x => x.CustomerName.Equals(input.CustomerName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.ProductNo), x => x.ProductNo.Contains(input.ProductNo))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null, x => x.AddTime >= input.StartCreationTime && x.AddTime.AddDays(-1) <= input.EndCreationTime)


                .Select((x, bu) =>
                    new ExportIUDefectiveOutput()
                    {
                        InstanceNumber = x.InstanceNumber,
                        BusinessDivision = x.BusinessDivision,
                        Company = x.Company,
                        BusinessDivisionType = x.BusinessDivisionType,
                        ProductType = x.ProductType,
                        CustomerName = x.CustomerName,
                        SellServeName = x.SellServeName,
                        SellServePhone = x.SellServePhone,
                        ProductNo = x.ProductNo,
                        ProductName = x.ProductName,
                        ProductGZPC1 = x.ProductGZPC1,
                        ProductGZWeight1 = x.ProductGZWeight1,
                        ProductGZPC2 = x.ProductGZPC2,
                        ProductGZWeight2 = x.ProductGZWeight2,
                        ProductGZPC3 = x.ProductGZPC3,
                        ProductGZWeight3 = x.ProductGZWeight3,
                        ProductGZRemark = x.ProductGZRemark,
                        ProductJSBRemark = x.ProductJSBRemark,
                        ProductGZTime = x.ProductGZTime.ToString("yyyy-MM-dd HH:mm:ss"),
                        JFRYName = x.JFRYName,
                        ProductGZBegTime = x.ProductGZBegTime.ToString("yyyy-MM-dd HH:mm:ss"),
                        AbnormalType = x.AbnormalType,
                        ProductGZRemark1 = x.ProductGZRemark1,
                        JSFWGZWeight = x.JSFWGZWeight,
                        JSFWGZWeightRank = x.JSFWGZWeightRank,
                        JSFWGZWeightRemark = x.JSFWGZWeightRemark,
                        JSFWGZDivision = x.JSFWGZDivision,
                        JSFWGZWeightRemark1 = x.JSFWGZWeightRemark1,
                        ProductNoGZH = x.ProductNoGZH,
                        ProductNameGZH = x.ProductNameGZH,
                        ProductGZHPC1 = x.ProductGZHPC1,
                        ProductGZHWeight1 = x.ProductGZHWeight1,
                        ProductGZHPC2 = x.ProductGZHPC2,
                        ProductGZHWeight2 = x.ProductGZHWeight2,
                        ProductGZHPC3 = x.ProductGZHPC3,
                        ProductGZHWeight3 = x.ProductGZHWeight3,
                        ProductGZHRemark = x.ProductGZHRemark,
                        ProductGZHProject = x.ProductGZHProject,
                        ProductGZHGZProject = x.ProductGZHGZProject,
                        ShippingArrangement = x.ShippingArrangement,
                        TrialRunTime = x.TrialRunTime.ToString("yyyy-MM-dd"),
                        TrialRun = x.TrialRun,
                        ReplacementRate = x.ReplacementRate,
                        ConstructabilityPerformance = x.ConstructabilityPerformance,
                        TrialConclusion = x.TrialConclusion,
                        QualityPerformance = x.QualityPerformance,
                        TrialConclusionRemark = x.TrialConclusionRemark,
                        ReformConclusion = x.ReformConclusion,
                        ReformConclusionRemark = x.ReformConclusionRemark,
                        ProjectResolution = x.ProjectResolution,
                        ProjectResolutionRemark = x.ProjectResolutionRemark,
                        ApproveEnd = x.ApproveEnd,
                        CcUsersName = x.CcUsersName,
         


                        OrderStatus = bu.ProcessStatusName,
                        CreateTime = bu.StartTime.ToString("yyyy-MM-dd HH:mm:ss"),
                        UserName = bu.StartUserName,
                        //LatelyActivityName = bu.,
                        FinishTime = bu.FinishTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),


                    }).MergeTable().Distinct().OrderBy(ins => ins.InstanceNumber, OrderByType.Desc);

            return listQueryable;
        }

        #endregion

        #region IU投诉报表导出Export1Async
        /// <summary>
        /// 报表导出数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<ExportIUDefectiveOutput>> Export1Async(GetIUDefectiveInput input)
        {
            //await UpdateOrderStatus(input);
            RefAsync<int> totalCount = 0;
            var listQueryable = GetQueryableExport1(input);
            var listViewDto = await listQueryable.ToListAsync();
            //var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);



            var i = 1;
            listViewDto.ForEach(x => x.SerialNumber = i++.ToString());
            return listViewDto;
        }

        #endregion
    }
}
